package controllers;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

public class CheckDomainExpireServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		String tld = (String) request.getAttribute("tld");
		String length = (String) request.getAttribute("length");
		String content = "";
		String strs = "";
		
		if (tld == null) {
			tld = "";
		}
		
		if (length == null) {
			length = "10";
		}
		
		try {
			URL url = new URL("http://107.21.108.48:8080/expiringdomain/newexpiring");
	        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
	        connection.setDoOutput(true);
	        connection.setReadTimeout(500000);
			connection.setConnectTimeout(1000000);
	        connection.setRequestMethod("POST");
	        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
	        OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
	        writer.write("tld=" + tld);
	        writer.write("&length="+length);
	        writer.close();
	        
	        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
	        	
	        	 BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    			
    			while(1==1)
    			{
    				String str = reader.readLine();
    				if(str==null) break;
    				content+=str;
    				
    			}
	        }
			Document doc = Jsoup.parse(content);
			strs = doc.select("body").html();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		//Cache header
		response.addHeader("Cache-Control", "public, max-age=60000");
		
		request.setAttribute("content", strs);
		request.setAttribute("tld", tld);
		request.setAttribute("length", length);
		try {
			request.getRequestDispatcher("/pages/check_expire.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
}
